/*
 * QTeXPreview
 * Copyright (C) 2008, Philip Pronin (philip.pronin@gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <QFile>

#include "tex.h"

TeXFrontEnd* TeXFrontEnd::create(QObject* parent) {
	return new MimeTeX(parent);
}

#ifdef Q_WS_WIN
const QString MimeTeX::mimetexFilename = "mimetex/mimetex.exe";
#else //Q_WS_WIN
const QString MimeTeX::mimetexFilename = "mimetex/mimetex.cgi";
#endif //Q_WS_WIN

MimeTeX::MimeTeX(QObject* parent) : TeXFrontEnd(parent), queued(false) {
	process = new QProcess(this);
	connect(process, SIGNAL(finished(int,QProcess::ExitStatus)),
		SLOT(finished(int,QProcess::ExitStatus)));
	connect(process, SIGNAL(started()), SIGNAL(renderStarted()));
	
	QFile file(mimetexFilename);
	file.setPermissions(file.permissions() | QFile::ExeUser);
}

MimeTeX::~MimeTeX() {
	if (process->state() != QProcess::NotRunning) process->kill();
}

void MimeTeX::start() {
	if (!queued || process->state() != QProcess::NotRunning) return;
	queued = false;

	if (equation.isEmpty()) emit renderFinished(QByteArray());
	else process->start(mimetexFilename, QStringList() << "-d" << (' ' + equation));
}

void MimeTeX::finished(int exitCode, QProcess::ExitStatus exitStatus) {
	QByteArray data = (!exitCode && exitStatus == QProcess::NormalExit)
		? process->readAllStandardOutput() : QByteArray();
	emit renderFinished(data);
	start();
}

bool MimeTeX::render(const QString& eq) {
	if (equation == eq) return false;

	queued = true; equation = eq;
	start();

	return true;
}

QByteArray MimeTeX::renderNow(const QString& eq) const {
	if (!eq.isEmpty()) {
		QProcess proc;
		proc.start(mimetexFilename, QStringList() << "-d" << (' ' + eq));
		proc.waitForFinished(-1);
		if (!proc.exitCode() && proc.exitStatus() == QProcess::NormalExit)
			return proc.readAllStandardOutput();
	}

	return QByteArray();
}

QString MimeTeX::getRenderFormat() const {
	return "gif";
}

QString MimeTeX::getRenderFormatFilter() const {
	return "Graphic Interchange Format (*.gif)";
}
